import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# 获取鸢尾花数据集
iris_datasets = load_iris()
# 划分数据集

# 参数1：预测值数组
# 参数2：结果数组
# 参数3：打乱随机数
X_train, X_test, y_train, y_test = train_test_split(
    iris_datasets['data'],
    iris_datasets['target'],
    random_state=0
)

# 使用K近邻算法分类

# 邻居个数为1
knn = KNeighborsClassifier(n_neighbors=1)

# 训练数据
knn.fit(X_train, y_train)

# 使用模型预测
X_new = np.array([[5, 2.9, 1, 0.2]])
prediction = knn.predict(X_new)

# 拿到对应的预测分类名称
result = iris_datasets['target_names'][prediction][0]
print("预测分类：{}".format(result))

# 使用knn自己的方法评估精度
score = knn.score(X_test, y_test)
print("该模型的预测准确率是：{}".format(score))
